 import * as CONFIG_URL from './config.js';
const globalData = getApp().globalData;
const URL = `https${globalData.url}`;
let app = getApp()
import { goLogin } from '../utils/util.js'

// promise 统一返回的函数 
const promise = (data) => {
  let { requestData, sign = 2, showLoad = true, isLogin=false } = data
  showLoad && wx.showLoading({title: '加载中...',})
  return new Promise((resolve, reject) => {
   
    const postData = {
      method: 'POST',
      header: {
        "content-type": "application/json",
        "token": wx.getStorageSync('token')
      }
    }

    const postFormData = {
      method: 'POST',
      header: {
        "content-type": "application/x-www-form-urlencoded",
        "token": wx.getStorageSync('token')
      }
    }

    const getData = {
      method: 'GET',
      header: {
        "content-type": "application/json",
        "token": wx.getStorageSync('token')
      }
    }

    const getFormData = {
      method: 'GET',
      header: {
        "content-type": "application/x-www-form-urlencoded",
        "token": wx.getStorageSync('token')
      }
    }
    wx.request(
      Object.assign(
        [postData, postFormData, getData, getFormData][sign], //sign默认为getData  可根据sign改变
        requestData, 
        {
          success: (res) => {
            if (res.header.token) wx.setStorageSync("token", res.header.token)
            if (res.statusCode === 200) {
              resolve(res.data)
            } else {
              reject('请求失败！')
            }
            res.data.resCode == 'LOGOUT' && !isLogin && goLogin()
            
          },
          fail(){
            console.log('556')
            reject('请求失败！')
          },
          complete(){
            wx.hideLoading()
            app.globalData.requestBool = false
          }
        }
      )
    )
  })
}

// 登录
const login = (accountname, password) => {
  let requestData = {
    url: URL + CONFIG_URL.URL_DATA.LOGIN,
    data: {
      accountname,
      password,
    }
  }
  return promise({ requestData , isLogin: true,sign: 1})
}

// 总览导航栏
const getStructure = () => {
  wx.showLoading({ title: '加载中...', })
  return new Promise((resolve, reject) => {
    wx.request({
      url: URL + CONFIG_URL.URL_DATA.GET_STRUCTURE,
      method: 'GET',
      header: {
        "token": wx.getStorageSync('token')
      },
      data: {
        userName: wx.getStorageSync('username'),
        token: wx.getStorageSync('token')
      },
      success(res) {
        if (res.header.token) wx.setStorageSync("token", res.header.token)
        
        if (res.statusCode === 200) {
          resolve(res.data)
        } else {
          wx.showToast({
            icon: 'none',
            title: '请求失败！',
          })
        }
        res.data.resCode == 'LOGOUT' && goLogin()
      },
      fail() {
        wx.showToast({
          icon: 'none',
          title: '请求失败！',
        })
      },
      complete() {
        wx.hideLoading()
        app.globalData.requestBool = false
      }
    })
  })
  
}

// 总览设备名称
const getdevicebystructure = ( treeID ) => {
  let requestData = {
    url: URL + CONFIG_URL.URL_DATA.GET_DEVICE_BY_STRUCTURE,
    data: {
      userName: wx.getStorageSync('username'),
      token: wx.getStorageSync('token'),
      treeID
    }
  }
  return promise({ requestData, sign: 1})
}

// 获取全部异常事件
const getallevent = ( commentable, page) => {
  let requestData = {
    url: URL + CONFIG_URL.URL_DATA.GET_ALL_EVENT,
    data: {
      deviceID: globalData.deviceName.deviceID,
      commentable,
      page,
      pageSize: 12,
      userName: wx.getStorageSync('username'),
      token: wx.getStorageSync('token'),
    }
  }
  return promise({ requestData })
}

// 编辑更新 UP_DATE_COMMENT
const upDateComment = (startTime, endTime, comment) => {
  let requestData = {
    url: URL + CONFIG_URL.URL_DATA.UP_DATE_COMMENT,
    data: {
      endTime,
      comment,
      startTime,
      token: wx.getStorageSync('token'),
      userName: wx.getStorageSync('username'),
      deviceID: globalData.deviceName.deviceID,
    }
  }
  return promise({ requestData, sign: 1})
}

// 获取状态总用时
const getStateTime = (startTime, endTime) => {
  let requestData = {
    url: URL + CONFIG_URL.URL_DATA.STATE_TIME,
    data: {
      endTime,
      startTime,
      token: wx.getStorageSync('token'),
      userName: wx.getStorageSync('username'),
      deviceID: globalData.deviceName.deviceID,
    }
  }
  return promise({ requestData })
}

// 添加异常事件
const addevent = (startTime, restore, comment) => {
  let requestData = {
    url: URL + CONFIG_URL.URL_DATA.ADD_EVENT,
    data: {
      restore,
      comment,
      startTime,
      token: wx.getStorageSync('token'),
      userName: wx.getStorageSync('username'),
      deviceID: globalData.deviceName.deviceID,
    }
  }
  return promise({ requestData , sign: 1})
}

// 统计图 DEVICESTATUS
const getCountPageData = ( data ) => {
  let { minute, startTime, endTime, size } = data;
  let requestData = {
    url: URL + CONFIG_URL.URL_DATA.DEVICESTATUS,
    data: {
      size: size === 2 ? size : '',
      minute,
      startTime,
      endTime,
      token: wx.getStorageSync('token'),
      userName: wx.getStorageSync('username'),
      deviceID: globalData.deviceName.deviceID,
      errorEvent: true
    }
  }
  return promise({ requestData })
}

// 获取状态趋势 GET_STATE_TREND
const getStateTrend = (data) => {
  let { minute, startTime, endTime } = data;
  let requestData = {
    url: URL + CONFIG_URL.URL_DATA.GET_STATE_TREND,
    data: {
      minute,
      startTime,
      endTime,
      token: wx.getStorageSync('token'),
      userName: wx.getStorageSync('username'),
      deviceID: globalData.deviceName.deviceID,
    }
  }
  return promise({ requestData })
}

// 产量统计表数据 
const productstatistics = (d) => {
  
  let { date, useDayPlay, hourPlay = '', dayPlay = '' } = d
  date = date.split('-');
  let requestData = {
    url: URL + CONFIG_URL.URL_DATA.PRODUCTSTATISTICS,
    data: {
      year: date[0],
      month: date[1],
      day: date[2],
      hourPlay,
      dayPlay,
      useDayPlay,
      token: wx.getStorageSync('token'),
      userName: wx.getStorageSync('username'),
      deviceID: globalData.deviceName.deviceID,
    }
  }
  return promise({ requestData })
}
// 产量统计表数据 
const getPlay = (d) => {
  d = d.split('-');
  let requestData = {
    url: URL + CONFIG_URL.URL_DATA.GET_PLAY,
    data: {
      year: d[0],
      month: d[1],
      day: d[2],
      useDayPlay: true,
      hourPlay: '',
      dayPlay: '',
      token: wx.getStorageSync('token'),
      userName: wx.getStorageSync('username'),
      deviceID: globalData.deviceName.deviceID,
    }
  }
  return promise({ requestData })
}

// 获取总览信息
const getView = (treeID, sceneID, devices = false) => {
  let requestData = {
    url: URL + CONFIG_URL.URL_DATA.GET_VIEW,
    data: {
      treeID,
      sceneID,
      devices,
      token: wx.getStorageSync('token'),
      userName: wx.getStorageSync('username'),
    }
  }
  return promise({ requestData, showLoad: false })
}

// 删除事件
const delItem = (id) => {
  let requestData = {
    url: URL + CONFIG_URL.URL_DATA.DEL_ITEM,
    data: {
      id,
      token: wx.getStorageSync('token'),
      userName: wx.getStorageSync('username'),
    }
  }
  return promise({ requestData, sign: 1 })
}

// 获取维保记录列表
const getMaintainList = (treeID,page) => {
  let requestData = {
    url: URL + CONFIG_URL.URL_DATA.GET_MAINTAIN_EVENTLIST,
    data: {
      treeID,
      pageSize: 50,
      pageNum: page,
      token: wx.getStorageSync('token'),
      userName: wx.getStorageSync('username'),
    }
  }
  return promise({ requestData, showLoad: false })
}

// 获取零件类型列表
const getDeviceType = (deviceID) => {
  let requestData = {
    url: URL + CONFIG_URL.URL_DATA.GET_DEVICE_TYPE,
    data: {
      deviceID
    }
  }
  return promise({ requestData })
}

// 获取商飞列表
const getComacList = (time, deviceID, partType='all', orderType = -1, orderScore = -1 ) => {
  let requestData = {
    url: URL + CONFIG_URL.URL_DATA.GET_COMAC_LIST,
    data: {
      time,// 查询日零点时间戳
      partType,// 零件列表
      orderType,  // 0是倒叙，1是正序，-1不使用该条件
      orderScore,
      deviceID,
    }
  }
  return promise({ requestData })
}

// 新增维保记录
const addMaintain = (startDate, endDate, comment, treeID) => {
  let requestData = {
    url: URL + CONFIG_URL.URL_DATA.ADD_MAINTAIN,
    data: {
      treeID,
      startDate: startDate,
      endDate: endDate,
      comment: comment,
      token: wx.getStorageSync('token'),
      userName: wx.getStorageSync('username'),
    }
  }
  return promise({ requestData, showLoad: false, sign: 1 })
}

// 删除维保记录
const delMaintain = (eventID) => {
  let requestData = {
    url: URL + CONFIG_URL.URL_DATA.DETEL_MAINTAIN,
    data: {
      eventIDs:eventID,
      token: wx.getStorageSync('token'),
      userName: wx.getStorageSync('username'),
    }
  }
  return promise({ requestData, sign: 1})
}

// 修改维保记录
const updateMaintain = (startDate, endDate, comment, treeID, eventID) => {
  let requestData = {
    url: URL + CONFIG_URL.URL_DATA.UPDATA_MAINTAIN,
    data: {
      treeID,
      eventID,
      startDate: startDate,
      endDate: endDate,
      comment: comment,
      token: wx.getStorageSync('token'),
      userName: wx.getStorageSync('username'),
    }
  }
  return promise({ requestData,sign: 1, showLoad: false })
}

// 获取异常信息列表
const getErrorInfo = (handleState, treeID, pageNum) => {
  let requestData = {
    url: URL + CONFIG_URL.URL_DATA.GET_ERROR_INFO,
    data: {
      // deviceID: globalData.deatilList[0].deviceID,
      pageSize: 10,
      pageNum,
      treeID,
      handleState,
      token: wx.getStorageSync('token'),
      userName: wx.getStorageSync('username'),
    }
  }
  return promise({ requestData, showLoad: false })
}

// 修改异常信息状态
const updateErrorInfoState = (handleState, eventID, message) => {
  let requestData = {
    url: URL + CONFIG_URL.URL_DATA.UPDATE_ERROR_INFO_STATE,
    data: {
      eventID,
      handleState,
      message,
      token: wx.getStorageSync('token'),
      userName: wx.getStorageSync('username'),
    }
  }
  return promise({ requestData, showLoad: false, sign: 1 })
}

// 获取设备配置信息
const getDevice = (treeID) => {
  let requestData = {
    url: URL + CONFIG_URL.URL_DATA.GET_DEVICE,
    data: {
      treeID,
      token: wx.getStorageSync('token'),
      userName: wx.getStorageSync('username'),
    }
  }
  return promise({ requestData, showLoad: false })
}
const loginOut = () => {
  let requestData = {
    url: URL + CONFIG_URL.URL_DATA.LOGIN_OUT,
  }
  return promise({ requestData })
}
// 获取comac账号的车床gague数据
const getComacGague = (deviceID) => {
  let requestData = {
    url: URL + CONFIG_URL.URL_DATA.COMAC_GAGUE,
    data: {
      deviceID,
      token: wx.getStorageSync('token'),
      userName: wx.getStorageSync('username'),
    }
  }
  return promise({ requestData, showLoad: false })
}
// 获取comac账号的今日零件完成度数据
const getComacToday = (deviceID) => {
  let requestData = {
    url: URL + CONFIG_URL.URL_DATA.COMAC_TODAY,
    data: {
      deviceID,
      token: wx.getStorageSync('token'),
      userName: wx.getStorageSync('username'),
    }
  }
  return promise({ requestData, showLoad: false })
}

module.exports = {
  login,
  getStructure,
  getdevicebystructure,
  getallevent,
  upDateComment,
  addevent,
  getCountPageData,
  getStateTrend,
  getPlay,
  productstatistics,
  getView,
  delItem,
  getStateTime,
  getMaintainList,
  addMaintain,
  updateMaintain,
  delMaintain,
  getErrorInfo,
  updateErrorInfoState,
  getDevice,
  loginOut,
  getComacGague,
  getComacToday,
  getDeviceType,
  getComacList,
}
